<?php
namespace app\mall\controller;

use think\Request;
use think\Db;
use think\Session;
use think\Controller;
use think\Config;
use Godok\Org\Auth;
use Wx\Xcx;
use think\Log;
/**
 * Login Controller
 */
class Login extends Controller
{

	// 登录  逻辑修改了 将就逻辑乱改的代码
	public function index(){
		if (session('wxLogin')) { // 需要注册
			$this->error('请先注册','','register');
		}

	    $openid = session('openid');
	    !$openid && $this->error('请先登录','','wxlogin');

	    $data = Request()->param();
	    $info = Db::name('user')->where(['openid'=>$openid])->find();
	    if ($info) {
	    	if ($info['status'] == 1) {
	    		unset($info['password'],$info['pay_pws']);
	    		$userinfo = $data['userinfo'];
	    		if ($userinfo) {
	    			Db::name('user')->where(['openid'=>$openid])->update(['nickname'=>$userinfo['nickName'],'avatar'=>$userinfo['avatarUrl'],'last_login_time' => time()]);
	    			$info['nickname'] = $userinfo['nickName'];
	    			$info['avatar'] = $userinfo['avatarUrl'];
	    		}
	    		Auth::user($info);
	    		$this->success('success');
	    	}else if ($info['status'] == 2) {
	    		$this->error('请先注册','','register');
	    	}else{
	    		$this->error('账号禁用','','disable');
	    	}
	    }else{
	    	$this->error('请先注册','','wxlogin');
	    }
	}

    // 微信小程序登录
	public function wxLogin(){
	    $jscode = Request()->param('code');
	    $config = Config::get('wx.xcx');
    	$xcx = new Xcx($config);
    	$re = $xcx->sessionKey($jscode);
    	if ($re) {
    		
    		$data = [
				'openid'        => $re['openid'],
				'session_key'   => $re['session_key']
    		];
    		$info = Db::name('user')->where(['openid'=>$re['openid']])->find();
    		if ($info) {
    			session('openid',$re['openid']);
    			Db::name('user')->where(['openid'=>$re['openid']])->update($data);
    			$this->success('success');
    		}else{
    			session('wxLogin',$data);
    			$this->error('请先注册','','register');
    			// $data['register_time'] = time();
    			// Db::name('user')->insertGetId($data);
    		}
    		// $this->success('success');
    	}else{
    		$this->error('error','',$xcx->getError());
    	}
	}
    /**
     * 退出
     */
    // http://127.0.0.1/auth/Login/logout
    public function logout()
    {
        Auth::clean();
        $this->success('退出成功、前往登录页面');
    }


	/* 用户注册 */
    public function register()
    {
    	Log::record('register','error');
    	Log::record(session('wxLogin'),'error');
    	Log::record(session('openid'),'error');

    	$openid = session('wxLogin.openid');
	    !$openid && $this->error('请先登录','','wxlogin');

    	$param = Request()->param();

    	$iv = $param['iv'];
    	$encryptedData = $param['encryptedData'];
    	$session_key = session('wxLogin.session_key');

    	Log::record(['vi'=>$iv,'encryptedData'=>$encryptedData,'session_key'=>$session_key],'error');

    	$config = Config::get('wx.xcx');
    	$xcx = new Xcx($config);
		$re = $xcx->wxBizDataCrypt($encryptedData,$iv,$session_key);

		Log::record($re,'error');
    	if ($re['status']) {
    		$re_up = false;

    		//看用户是否存在 先以电话为准
    		$user = Db::name('user')->where(['username'=>$re['info']['phoneNumber']])->find();
    		if ($user) {
    			//更新用户
    			$re_up = Db::name('user')->where(['id'=>$user['id']])->update(['session_key'=>$session_key,'openid'=>$openid,'register_time'=>time()]);
    			Log::record('更新用户','error');
    			Log::record($re_up,'error');
    		}else{
    			//新增用户
    			$data = [
					'username'      => $re['info']['phoneNumber'],
					'phone'         => $re['info']['phoneNumber'],
					'session_key'   => $session_key,
					'openid'        => $openid,
					'register_time' => time(),
					'status'        => 1
	    		];
    			$user_id = Db::name('user')->insertGetId($data);
    			//新增一个店铺
    			$shop_id = Db::name('shop')->insertGetId(['user_id'=>$user_id,'shop_no'=>$data['phone'],'create_time'=>date('Y-m-d H:i:s')]);
    			Log::record('插入用户','error');

    			$re_up = Db::name('user')->where(['username'=>$data['phone']])->update(['shop_id'=>$shop_id]); //更新用户状态
    			Log::record($re_up,'error');
    		}

    		if ($re_up!==false) {
    			session('openid',$openid);
    			session('wxLogin',null);
    			$this->success('注册成功');
    		}else{
    			Log::record('注册失败1','error');
    			$this->error('注册失败1');
    		}
    	}else{
    		Log::record('注册失败2','error');
    		$this->error('注册失败2');
    	}
    }

    /* 店铺信息 */
	public function shop_info(){
		$data = Request()->only('shop_name,shop_owner,shop_province,shop_city,shop_district,shop_address','get');
		$data['user_id'] = session('tmp_uid');
		if (empty($data['user_id'])) {
			$this->error('请先登录','','login');
		}
		if (empty($data['shop_name'])) {
			$this->error('请填写店铺名');
		}
		if (empty($data['shop_owner'])) {
			$this->error('请填写负责人');
		}
		$isset = Db::name('shop')->where(['shop_name'=>trim($data['shop_name'])])->find();
		$isset && $this->error('店铺已存在');

		$re = Db::name('shop')->insertGetId($data);
		if($re){
			$res=db('user')->update(['id'=>$data['user_id'],'status'=>1]);
			session('tmp_uid',null);
			$info = Db::name('user')->where(['id'=>$data['user_id'],'deleted'=>['neq',1]])->find();
			Auth::user($info);
			$this->success('操作成功');
		}else{
			$this->error('操作失败');
		}
	}

	/* 获取验证码 */
	public function get_verify(){
		// session('code','123456');$this->success('获取验证码成功');
		// $phone=input('username');
		// $info=db('user')->where('username',$phone)->find();
		// if($info){
		// 	$this->error('该手机号已经被注册');
		// }else{
		// 	import('alidayu.TopSdk');
		// 	import('alidayu.top.TopClient');
		// 	import('alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
		// 	$appkey="23535194";
		// 	$secret="48953173553ad6ad6b306138f518d7f1";


		// 	$code=substr(str_shuffle("012345678901234567890123456789"), 0, 6);
		// 	$product="速冻在线";

		// 	$c = new \TopClient();
		// 	$c ->appkey = $appkey ;
		// 	$c ->secretKey = $secret ;
		// 	$req = new \AlibabaAliqinFcSmsNumSendRequest();
		// 	$req ->setExtend( "" );
		// 	$req ->setSmsType( "normal" );
		// 	$req ->setSmsFreeSignName( "注册验证" );
		// 	$req ->setSmsParam( "{code:'$code',product:'$product'}" );
		// 	$req ->setRecNum( $phone );
		// 	$req ->setSmsTemplateCode( "SMS_26310156" );
		// 	$resp = $c ->execute( $req );

		// 	if($resp){
		// 		session('code',$code);
		// 		$this->success('获取验证码成功');
		// 	}
		// }
	}

}

